package easy;

public class Solution_463 {
    public int islandPerimeter(int[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                count = count + isDAO(i, j, grid, 0) + isDAO(i, j, grid, 2);
                if (i == grid.length - 1) {
                    count += isDAO(i, j, grid, 1);
                }
                if (j == grid[i].length -1) {
                    count += isDAO(i, j, grid, 3);
                }
            }
        }
        return count;
    }

    private int isDAO(int i, int j, int[][] grid, int flag) {
        // flag 0上 1下 2左 3 右
        if (flag == 0) {
            if (i==0) {
                return grid[i][j];
            } else {
                return grid[i-1][j] ^ grid[i][j];
            }
        } else if (flag == 1) {
            if (i==(grid.length-1)) {
                return grid[i][j];
            } else {
                return grid[i+1][j] ^ grid[i][j];
            }
        } else if (flag == 2) {
            if (j==0) {
                return grid[i][j];
            } else {
                return grid[i][j-1] ^ grid[i][j];
            }
        } else if (flag == 3) {
            if (j==(grid[i].length-1)) {
                return grid[i][j];
            } else {
                return grid[i][j+1] ^ grid[i][j];
            }
        }
        return 0;
    }

    public int islandPerimeter1(int[][] grid) {
        int count = 0;
        int[][] flag_x = new int[grid.length + 1][grid[0].length];
        int[][] flag_y = new int[grid.length][grid[0].length + 1];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 1) {
                    flag_x[i][j]++;
                    flag_x[i+1][j]++;
                    flag_y[i][j]++;
                    flag_y[i][j+1]++;
                }
            }
        }
        for (int[] flagX : flag_x) {
            for (int x : flagX) {
                if (x == 1) {
                    count++;
                }
            }
        }
        for (int[] flagY : flag_y) {
            for (int y : flagY) {
                if (y == 1) {
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution_463 model = new Solution_463();
        System.out.println(model.islandPerimeter(new int[][]{{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}}));
        System.out.println(model.islandPerimeter(new int[][]{{1}}));
        System.out.println(model.islandPerimeter(new int[][]{{1, 0}}));
    }
}
